package cn.xiqi.cms.oper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xiqi.cms.beans.UserBean;
import cn.xiqi.cms.hibernate.DAO.UsrDAOImpl;
import cn.xiqi.cms.hibernate.beans.Accountinfo;
import cn.xiqi.cms.hibernate.beans.Usrinfo;
import cn.xiqi.cms.hibernate.service.UsrService;
import cn.xiqi.cms.hibernate.service.UsrServiceImpl;

public class UserOper {
	private UsrService service;
	
	public UserOper(){
		service = new UsrServiceImpl();
		service.setDao(new UsrDAOImpl());
	}
	
	public Map<String, Object> getAll(int page, int size){
		List<Usrinfo> records;
		List<Object> datas;
		Map<String, Object> map = new HashMap<>();
		int count;
		records = service.getAll(page, size);
		count = service.getCount("all");
		datas = toMap(records);
		map.put("total", count);
		map.put("rows", datas);
		map.put("page", page);
		map.put("size", size);
		return map;
	}
	
	public int getCount(String type){
		int count = service.getCount(type);
		return count;
	}
	
	public boolean delete(int userid){
		Usrinfo record = service.getByID(userid);
		AccountOper account = new AccountOper();
		boolean b = false;
		boolean userDelete = service.delete(record);
		boolean accountDelete = account.delete(userid);
		if(userDelete && accountDelete)
			b = true;
		return b;
	}
	
	public int addUser(String name, int sex, int depart, int level, int role){
		int userid;
		Usrinfo record;
		
		record = new Usrinfo(name, sex, depart, role, level, 0);
		userid = service.insert(record);
		return userid;
	}
	
	public boolean update(int userid, String name, int depart, int level, int role, int sex, int stat){
		boolean b;
		Usrinfo record;
		
		record = service.getByID(userid);
		record.setDepart(depart);
		record.setLevel(level);
		record.setName(name);
		record.setRoleID(role);
		record.setSex(sex);
		record.setStat(stat);
		b = service.update(record);
		return b;
	}
	
	public Map<String, Object> getByID(int userid){
		Map<String, Object> map = new HashMap<>();
		AccountOper accountoper = new AccountOper();
		Usrinfo user = service.getByID(userid);
		Accountinfo account = accountoper.getByUser(userid);
		map.put("account", account.getUsername());
		map.put("name", user.getName());
		map.put("depart", user.getDepart());
		map.put("sex", user.getSex());
		map.put("level", user.getLevel());
		map.put("role", user.getRoleID());
		return map;
	}
	
	private List<Object> toMap(List<Usrinfo> records){
		List<Object> datas = new ArrayList<>();
		
		for(Usrinfo record:records){
			UserBean data = new UserBean(record);
			datas.add(data);
		}
		return datas;
	}
}
